﻿using System;
using System.Text;
using Newtonsoft.Json;
namespace Yt.Core.IPC
{
    /// <summary>
    /// Json序列化帮助类
    /// </summary>
    internal static class JsonSerializeHelper
    {
        public static string ToJson(object obj)
        {
            if (obj == null) return null;
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Formatting = Formatting.Indented
            };
            return JsonConvert.SerializeObject(obj, settings);
        }
        public static T ToObject<T>(string json)
        {
            if (json == null) return default(T);
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Formatting = Formatting.Indented
            };
            return JsonConvert.DeserializeObject<T>(json, settings);
        }
        public static object ToObject(Type type, string json)
        {
            if (json == null) return default(object);
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Formatting= Formatting.Indented
            };
            return JsonConvert.DeserializeObject(json, type, settings);
        }

        public static string ToBase64String(string json)
        {
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(json));
        }
        public static string Base64StringToJson(string base64String)
        {
            return Encoding.UTF8.GetString(Convert.FromBase64String(base64String));
        }
    }
}
